<?php

class PembayaranController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';


	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
        
	public function actionCreate($add=0, $ok=1){
            
                $model=new Pembayaran;
                $model2 = array();
                for($i = 0; $i <= $add; $i++){
                    array_push($model2, new PesananPembayaran);
                }

                $adds = $add;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
                
                $model->ID_Pembayaran = $this->nextID();
                $cur = getdate();
                $model->Tgl_Pembayaran = $cur['mday'].'-'.$cur['mon'].'-'.$cur['year'];

		if(isset($_POST['PesananPembayaran'])&& $ok == 1)
		{
                        $valid = true;
                        for($i=0; $i <= $adds; $i++){
                            if(isset($_POST['PesananPembayaran'][$i]['ID_Pesanan'])){
                                $model2[$i]->ID_Pesanan = $_POST['PesananPembayaran'][$i]['ID_Pesanan'];
                                $model2[$i]->ID_Pembayaran = $model->ID_Pembayaran;
                                $valid = $valid && $model2[$i]->validate();
                            }
                        }
                        $valid = $valid && $model->validate();
                        $valid1 = true;
                        if(Yii::app()->user->isMember()){
                                    $member = Member::model()->findByPk(Yii::app()->user->name);
                                    $valid1 = ($member->Saldo > 60000*($adds+1));
                                    if($valid1 == false){
                                        for($i=0; $i <= $adds; $i++){
                                            $model2[$i]->addError('ID_Pesanan','You do not have enough money');
                                        }
                                    }
                        }
                        if($valid && $valid1){
                                for($i=0; $i <= $adds; $i++){
                                    $model2[$i]->save();
                                }
                                $model->save();
                                if(Yii::app()->user->isMember()){
                                    $member = Member::model()->findByPk(Yii::app()->user->name);
                                    $member->Saldo = $member->Saldo - 60000*($adds+1);
                                    $member->save();
                                }
				$this->redirect(array('view','id'=>$model->ID_Pembayaran));
                        }
		}

		$this->render('create',array(
			'model'=>$model,
                        'model2'=> $model2,
                        'adds'=>$adds,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Pembayaran']))
		{
			$model->attributes=$_POST['Pembayaran'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->ID_Pembayaran));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Pembayaran');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Pembayaran('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Pembayaran']))
			$model->attributes=$_GET['Pembayaran'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Pembayaran::model()->findByPk($id);
                $pesanan=PesananPembayaran::model()->findAllByAttributes(array('ID_Pembayaran'=>$id));
                $array = array('ID_Pembayaran'=>$model->ID_Pembayaran, 'Tgl_Pembayaran'=>$model->Tgl_Pembayaran);
		for($i=0; $i < count($pesanan);$i++){
                    $array['ID_Pesanan'.($i+1)] = $pesanan[$i]->ID_Pesanan;
                }
                if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $array;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='pembayaran-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
        }

        public function generateID($count)
        {
            $id1 = (int)($count/1000000);
            if($id1 < 10)
                $id1 = '0'.(string)$id1;
            $id2 = (string)($count/10000) % 100;
            if($id2 < 10)
                $id2 = '0'.(string)$id2;
            $id3 = (string)($count/100) % 100;
            if($id3 < 10)
                $id3 = '0'.(string)$id3;
            $id4 = (string)($count) % 100;
            if($id4 < 10)
                $id4 = '0'.(string)$id4;
            return $id1.'-'.$id2.'-'.$id3.'-'.$id4;
        }

        public function nextID(){
            $count = 1;
            $pembayaran = Pembayaran::model();
            $id = $this->generateID($count);
            $found = $pembayaran->exists($condition = 'ID_Pembayaran = :id', $param = array(':id'=>$id));
            while($found){
                $count = ($count + 1)%100000000;
                $id = $this->generateID($count);
                $found = $pembayaran->exists($condition = 'ID_Pembayaran = :id', $param = array(':id'=>$id));
            }
            return $id;
        }
}
